﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;

namespace ETADTools.Lib
{
  public static class FieldExportInterfaceExtension
  {
    /// <summary>
    /// Convert to sql export select
    /// </summary>
    /// <returns></returns>
    public static string ToSqlExportSelect(this Field field)
    {
      // Sample
      // ---------------------------------------------------------------------
      // SELECT
      //   ISNULL(LocalEmpCode, ''),
      //   ISNULL(CONVERT(NVARCHAR(11), Date, 112), ''),
      //   ISNULL(CAST(CAST(Amount AS DECIMAL(28,2)) AS NVARCHAR(55)), '')

      StringBuilder sql = new StringBuilder();

      // Datetime
      if (field.FieldType.GetSize() == "11")
      {
        sql.AppendFormat("ISNULL(CONVERT(NVARCHAR(11), {0}, 112), '')", field.FieldName);
      }
      // Decimal
      else if (field.FieldType.GetSize() == "55")
      {
        sql.AppendFormat("ISNULL(CAST(CAST({0} AS DECIMAL(28,2)) AS NVARCHAR(55)), '')", field.FieldName);
      }
      // Everything else
      else
      {
        sql.AppendFormat("ISNULL({0}, '')", field.FieldName);
      }

      return sql.ToString();
    }

    /// <summary>
    /// Convert to sql export row content.
    /// </summary>
    /// <returns></returns>
    public static string ToSqlExportRowContent(this Field field)
    {
      //TODO: Sample
      // ---------------------------------------------------------------------

      StringBuilder sql = new StringBuilder();

      if (field.FieldType.GetSize() == "11" || 
          field.FieldType.GetSize() == "44" ||
          field.FieldType.GetSize() == "55")
      {
        sql.AppendFormat("{0}{1}", field.FieldType.ToDeclareStyle(), field.FieldName);
      }
      else
      {
        sql.AppendFormat("REPLACE({0}{1}, '|', '\\|')", field.FieldType.ToDeclareStyle(), field.FieldName);
      }
      sql.Insert(0, "SET @strRowContent = @strRowContent + ");

      return sql.ToString();
    }
  }
}
